package com.android.nearshop.app.activity.main;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ListView;

import com.android.nearshop.R;
import com.android.nearshop.app.MyApplication;
import com.android.nearshop.app.activity.common.TemplateActivity;
import com.android.nearshop.app.adapter.listadapter.ArrayExpandListAdapter.ExpandData;
import com.android.nearshop.app.adapter.listadapter.CategoryListAdapter;
import com.android.nearshop.app.adapter.listadapter.Text3ListAdapter;
import com.android.nearshop.app.adapter.listadapter.Text3ListAdapter.Text3Item;
import com.android.nearshop.app.widget.LoadableView;
import com.android.nearshop.app.widget.TitleBar;
import com.android.nearshop.app.widget.TitleBar.OnTitleClickListener;
import com.android.nearshop.business.cache.DataCacheManager;
import com.android.nearshop.io.protocol.out.Area;
import com.android.nearshop.io.protocol.out.Catalogy;
import com.android.nearshop.util.Constant;
import com.android.nearshop.util.NotifyListener;

/*********************************************************
 * @author : zhaohua
 * @version : 2012-8-22
 * @see : 添加筛选镇区 与 商家分类 综合选择
 * @Copyright : copyrights reserved by personal 2007-2011
 **********************************************************/
public class FilterActivity extends TemplateActivity 
implements OnClickListener,OnItemClickListener
{
    public static final int CODE_REQUEST = 0x8804;
    private LoadableView mNormalLoadingView;
    private ListView listView;
    private ExpandableListView expandList;
    private CategoryListAdapter cateAdapter;
    private Text3ListAdapter    areaAdapter;
    private Button area_sel;
    private Button cate_sel;
    private boolean onlyArea;
    private int mode = 0;
    private ArrayList<Integer> selectedList;
    
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState); 
        selectedList = getIntent().getIntegerArrayListExtra(Constant.TAG_CATEGORYS);
        setContentView(R.layout.activity_filter);
        initViews();     
        loadData(0);
    }
    
    @Override
    protected void setupTitleBar(TitleBar titleBar)
    {
//        titleBar.setLeftVisible(false);
        titleBar.setRigthText(R.string.sure);
        titleBar.setTitle(R.string.filter_tx);
        titleBar.setOnTitleClickListener(new OnTitleClickListener()
        {
            @Override
            public void onRightClick()
            {
                onOK();
            }
        },false, true);
    }
    
    @Override
    public void onClick(View v)
    {
        switch(v.getId())
        {
            case R.id.area_sel:
            {                
                listView.setVisibility(View.VISIBLE);
                expandList.setVisibility(View.GONE);
                
                area_sel.setBackgroundResource(R.drawable.select_left_tap);
                cate_sel.setBackgroundResource(R.drawable.select_right); 
                
                area_sel.setTextColor(getResources().getColor(R.color.white));
                cate_sel.setTextColor(getResources().getColor(R.color.black));
                
                loadData(0);
                break;
            }
            case R.id.cate_sel:
            {
                listView.setVisibility(View.GONE);
                expandList.setVisibility(View.VISIBLE);
                
                area_sel.setBackgroundResource(R.drawable.select_left);
                cate_sel.setBackgroundResource(R.drawable.select_right_tap);
                
                area_sel.setTextColor(getResources().getColor(R.color.black));
                cate_sel.setTextColor(getResources().getColor(R.color.white));
                
                loadData(1);
                break;
            }
        }
    }
    
    @Override
    public void refreshView()
    {
        loadData(mode);
    }
    
    private void initViews()
    {
    	Intent intent = getIntent();
    	if(intent != null && intent.getBooleanExtra(Constant.LOCATION_ONLY, false))
    	{
    		onlyArea = true;
    		findViewById(R.id.selection_panel).setVisibility(View.GONE);
    	}
    	
    	mNormalLoadingView = (LoadableView)findViewById(R.id.loadView);
    	mNormalLoadingView.setActivity(this);
    	
        listView = (ListView)findViewById(R.id.listView);
        listView.setDivider(getResources().getDrawable(R.drawable.content_div));
        areaAdapter = new Text3ListAdapter(this);
        listView.setAdapter(areaAdapter);
        listView.setOnItemClickListener(this);
        
        expandList = (ExpandableListView)findViewById(R.id.expandableListView);
        cateAdapter = new CategoryListAdapter(this,true);
        expandList.setAdapter(cateAdapter);
        
        area_sel = (Button)findViewById(R.id.area_sel);
        cate_sel = (Button)findViewById(R.id.cate_sel);
        area_sel.setOnClickListener(this);
        cate_sel.setOnClickListener(this);
        
        area_sel.setBackgroundResource(R.drawable.select_left_tap);
        area_sel.setTextColor(getResources().getColor(R.color.white));
        expandList.setVisibility(View.GONE);
    }
        
    private void loadData(int type)
    {
        mode = type;
        if(type == 0)
        {
            if( areaAdapter.getCount() > 0)
            {
                return;
            }
        }else
        {
            if( cateAdapter.getGroupCount() > 0)
            {
                return;
            }
        }
        mNormalLoadingView.showLoadingView();
        if(type == 0)
        {
        DataCacheManager.getInstance().getAreaList(
                new NotifyListener<List<Area>>()
        {
            @Override
            public void onSucceed(List<Area> result)
            {
                  if (result != null)
                  {
                      int size = result.size();
                      List<Text3Item> list = new ArrayList<Text3Item>(size);

                      // alter by huangyue 可以选着全部地区
                      Area one = new Area();
                      one.areaId = 0;
                      one.areaName = MyApplication.getContext().getString(R.string.all);
                      list.add(one);
                      // end

                      for (int i = 0; i < size; i++)
                      {
                          list.add(result.get(i).setCheckVisible(true));
                      }
                      areaAdapter.setList(list);
                      
                      mNormalLoadingView.showMainView();
                  } else
                 {
                      mNormalLoadingView.showLoadingErrView(R.string.no_result, false);   
                 }
             }
            
            @Override
            public void onError(int resultCode)
            {
                mNormalLoadingView.showLoadingErrView(false);
            }
        });
        }else
        {
        DataCacheManager.getInstance().getCateList(
                new NotifyListener<List<Catalogy>>()
        {
            @Override
            public void onSucceed(List<Catalogy> result)
            {
                if(result != null)
                {
                    int size = result.size();
                    List<ExpandData<Catalogy, Catalogy>> list = new ArrayList<ExpandData<Catalogy,Catalogy>>(size + 1);
                    ExpandData<Catalogy, Catalogy> one = null;
                    // all header
                    one = cateAdapter.getAllHeader();
                    haveSelcted((Catalogy)one.group);
                    list.add(one);
                    // other category
                    for(int i = 0; i< size; i++)
                    {
                        haveSelcted(result.get(i));
                        one = new ExpandData<Catalogy, Catalogy>(result.get(i), result.get(i).catalogyList);
                        list.add(one);
                    }                    
                    cateAdapter.setList(list);
                    mNormalLoadingView.showMainView();
                }else
                {
                    mNormalLoadingView.showLoadingErrView(R.string.no_result, false);   
                }
            }
            @Override
            public void onError(int resultCode)
            {
                mNormalLoadingView.showLoadingErrView(false);
            }
        });
        }
    }
    
    private void haveSelcted(Catalogy group)
    {
        if(selectedList != null && selectedList.size() > 0)
        {
            if(selectedList.contains(group.catalogyId))
            {
                group.checked(false, false, true);
            }else
            {
                if(group.catalogyList != null && group.catalogyList.size() > 0)
                {
                    for(Catalogy child : group.catalogyList)
                    {
                        if(selectedList.contains(child.catalogyId))
                        {
                            child.checked(false, false, true);
                        }
                    }
                }
            }
        }
    }
    
    private void onOK()
    {
        Area one = getSelArea();
        Intent intent = new Intent();
        intent.putExtra(Constant.TAG_CITY, (Serializable)one);       
        if(!onlyArea)
        {
	        intent.putIntegerArrayListExtra(Constant.TAG_CATEGORYS, cateAdapter.getSelIds());
	        //alter by huangyue 保存上次筛选的记录
	        writeSortinfo(one != null ? one.areaId : 0, cateAdapter != null ? cateAdapter.getSelIds() : null);
	        //alter by huangyue 保存上次筛选的记录 end
        }
        setResult(RESULT_OK, intent);
        finish();
    }

    private void writeSortinfo(int areaId, List<Integer> categorys)
    {
        FileOutputStream fos = null;

        try
        {
            JSONObject json = new JSONObject();
            json.put(Constant.TAG_CITY, areaId);
            if (categorys != null && categorys.size() > 0)
            {
                JSONArray jsonArray = new JSONArray();
                for (Integer id : categorys)
                {
                    jsonArray.put(id);
                }

                json.put(Constant.TAG_CATEGORYS, jsonArray);
            }

            fos = openFileOutput(Constant.SORT_RECODE_FILE_NAME, MODE_PRIVATE);
            fos.write(json.toString().getBytes());
            fos.flush();
        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            if (fos != null)
            {
                try
                {
                    fos.close();
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
    
    private Area getSelArea()
    {
        int size = areaAdapter.getCount();
        for(int i= 0 ; i<size; i++)
        {
            Area one = (Area)areaAdapter.getItem(i);
            if(one.checked(false, true, false))
            {
                return one;
            }
        }
        return null;
    }
    
    public static void startActivityResult(Activity context)
    {        
        startActivityResult(context, null);
    }
    
    public static void startActivityResult(Activity context,ArrayList<Integer> selectedList)
    {        
        context.startActivityForResult(getStartActivity(context,selectedList), CODE_REQUEST);
    }
    
    public static Intent getStartActivity(Activity context,ArrayList<Integer> selectedList)
    {        
        Intent intent = new Intent(context, FilterActivity.class);
        if(selectedList != null && selectedList.size() > 0)
        {
            intent.putIntegerArrayListExtra(Constant.TAG_CATEGORYS, selectedList);
        }
        return intent;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        int size = areaAdapter.getCount();
        if(areaAdapter != null &&  size > 0)
        {
            Area selceted = (Area)areaAdapter.getItem(position);
            if(selceted.checked(false, true, false))
            {
                selceted.checked(false, false, false);
            }else
            {
                selceted.checked(false, false, true);
                for (int i = 0; i < size; i++)
                {
                    Area one = (Area) areaAdapter.getItem(i);
                    if (i != position)
                    {
                        one.checked(false, false, false);
                    }
                }
            }
            areaAdapter.notifyDataSetChanged();
        }
    }
}
